package secret.hehe.com.secret.Activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.doInsert;
import static secret.hehe.com.secret.Util.Util.doSelect;
import static secret.hehe.com.secret.Util.Util.getPath;
import static secret.hehe.com.secret.Util.Util.pxtodip;
import static secret.hehe.com.secret.Util.Util.setImageSize;


public class SendActivity extends AppCompatActivity {
    private String sendId;
    private EditText recvId;
    private EditText title;
    private int message_type=1;
    private EditText message_text;
    private String message_text_toString;
    private int hidden_type=1;
    private String hidden_text="";
    private String abstract_text;
    private int isHidden=0;
    private String keybody="";
    private String sendTime="";
    private String jsonString;
    private int canClick=1;
    private AlertDialog alertDialog;
    private PopupWindow hiddenType;
    private TextView progress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        title = (EditText)findViewById(R.id.send_title);
        recvId = (EditText)findViewById(R.id.send_name);
        message_text = (EditText)findViewById(R.id.send_contant);

        Intent intent = getIntent();
        //接受数据
        try {
            sendId=(String) intent.getSerializableExtra("sendId");
            recvId.setText((String)intent.getSerializableExtra("recvId"));
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止杀死变量
        if (savedInstanceState != null) {
            try {
                canClick = savedInstanceState.getInt("canClick");
                sendId = savedInstanceState.getString("sendId");
                message_type = savedInstanceState.getInt("message_type");
                hidden_type = savedInstanceState.getInt("hidden_type");
                hidden_text = savedInstanceState.getString("hidden_text");
                isHidden = savedInstanceState.getInt("isHidden");
                keybody = savedInstanceState.getString("keybody");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //添加收件人
        ImageView add_receives = (ImageView)findViewById(R.id.add_receives);
        add_receives.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SendActivity.this, SearchMailActivity.class);
                intent.putExtra("userId",sendId);
                intent.putExtra("isMail",0);
                startActivityForResult(intent,1001);
            }
        });

        //添加图片
        ImageView add_image = (ImageView)findViewById(R.id.add_image);
        add_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Android6.0后读写sd卡权限需要动态申请
                if (ContextCompat.checkSelfPermission(SendActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            2000);
                }else{
                    insertImage();
                }
            }
        });

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
            case R.id.send_add: {//内含隐秘信息
                try {
                    Intent intent = new Intent(SendActivity.this, SendHiddenActivity.class);
                    intent.putExtra("hidden_type",hidden_type);
                    intent.putExtra("hidden_text",hidden_text);
                    startActivityForResult(intent,1001);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
            }
            case R.id.send_message:{//发送按钮
                if(canClick==1){
                    canClick=0;
                    if(checkText()){
//                        progress = new TextView(this);
//                        progress.setText("发送中");
                        //设置密码
                        final EditText et = new EditText(this);
                        et.setInputType(InputType.TYPE_CLASS_NUMBER);
                        et.setText(keybody);
                        //限制密码最多4位
                        InputFilter[] filters = {new InputFilter.LengthFilter(4)};
                        et.setFilters(filters);
                        new AlertDialog.Builder(this).setTitle("输入密码")
                                .setView(et)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String input = et.getText().toString();
                                        keybody = input;
                                        //发送
                                        new AlertDialog.Builder(SendActivity.this).setTitle("提示")
                                                .setMessage("确定要发送吗")
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        alertDialog = new AlertDialog.Builder(SendActivity.this).setTitle("提示")//设置对话框标题
                                                                .setMessage("发送中")
                                                                //.setView(progress)
                                                                .setCancelable(false)
                                                                .show();
                                                        message_text_toString = message_text.getText().toString();
                                                        JSONObject imgList = readImgText(message_text_toString+hidden_text);
                                                        Iterator it = imgList.keys();
                                                        while (it.hasNext()){
                                                            try {
                                                                String src = it.next().toString();
                                                                String alt = imgList.getString(src);
                                                                message_text_toString = message_text_toString.replace(alt,"");
                                                                hidden_text = hidden_text.replace(alt,"");
                                                            }catch (JSONException e){
                                                                e.printStackTrace();
                                                            }

                                                        }
                                                        Util util = new Util();
                                                        if(imgList.length()==0){
                                                            sendAllMessage();
                                                        }else{
                                                            Util.uploadFileThread uploadFileThread = util.new uploadFileThread("/email/sendImgs",getApplicationContext(),imgList,handler,2);
                                                            uploadFileThread.start();
                                                        }




                                                    }
                                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                canClick=1;
                                                return;
                                            }
                                        }).show();
                                        return;
                                    }
                                }).show();

                    }else{
                        canClick=1;
                    }
                }
                return true;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //刷新信息
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 1002) {
            //接受隐藏信息
            try{
                hidden_type =(int) data.getSerializableExtra("hidden_type");
                hidden_text =(String) data.getSerializableExtra("hidden_text");
                isHidden =(int) data.getSerializableExtra("isHidden");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (requestCode == 1001 && resultCode == 1000) {
            //接受添加收件人
            try{
                String uid = (String)data.getSerializableExtra("userId");
                StringBuilder newReceive = new StringBuilder(recvId.getText().toString().replace(" ",""));
                if(newReceive.toString().equals("")){

                }else{
                    newReceive.append(";");
                }
                newReceive.append(uid);
                recvId.setText(newReceive);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if (requestCode == 1000 && resultCode == RESULT_OK) {
            //相册
            final DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);

            final Uri selectedImage = data.getData();
            View customView = getLayoutInflater().inflate(R.layout.menu_hidden, null, false);
            hiddenType = new PopupWindow(customView, metric.widthPixels/360*200,metric.widthPixels/360*178);
            hiddenType.setBackgroundDrawable(new BitmapDrawable());
            hiddenType.setOutsideTouchable(true);
            hiddenType.setTouchable(true);
            hiddenType.setFocusable(true);
            hiddenType.showAtLocation(SendActivity.this.findViewById(R.id.activity_send), Gravity.CENTER, 0, 0);
            //图片隐藏文字
            Button textType = (Button) customView.findViewById(R.id.set_hidden_type_text);
            textType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final View customViewText = getLayoutInflater().inflate(R.layout.menu_hidden_text, null, false);
                    final PopupWindow hiddenText = new PopupWindow(customViewText, metric.widthPixels/360*300,metric.widthPixels/360*300);
                    hiddenText.setBackgroundDrawable(new BitmapDrawable());
                    hiddenText.setOutsideTouchable(true);
                    hiddenText.setTouchable(true);
                    hiddenText.setFocusable(true);
                    hiddenText.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    hiddenText.showAtLocation(SendActivity.this.findViewById(R.id.activity_send), Gravity.CENTER, 0, 0);
                    Button setHiddenTextFinish = (Button) customViewText.findViewById(R.id.set_hidden_text_finish);
                    setHiddenTextFinish.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //完成按钮
                            EditText imgHiddenText = (EditText) customViewText.findViewById(R.id.set_hidden_text);
                            insertImfo(selectedImage,imgHiddenText.getText().toString());
                            if (hiddenText != null && hiddenText.isShowing()) {
                                hiddenText.dismiss();
                            }
                            if (hiddenType != null && hiddenType.isShowing()) {
                                hiddenType.dismiss();
                            }
                        }
                    });
                    Button setHiddenTextDelete = (Button) customViewText.findViewById(R.id.set_hidden_text_delete);
                    setHiddenTextDelete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //取消按钮
                            if (hiddenText != null && hiddenText.isShowing()) {
                                hiddenText.dismiss();
                            }
                        }
                    });
                }
            });

            Button noHidden = (Button) customView.findViewById(R.id.set_no_hidden);
            noHidden.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    insertImfo(selectedImage,"");
                    if (hiddenType != null && hiddenType.isShowing()) {
                        hiddenType.dismiss();
                    }
                }
            });


        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putInt("canClick", canClick);
        outState.putString("sendId",sendId);
        outState.putInt("message_type",message_type);
        outState.putInt("hidden_type",hidden_type);
        outState.putString("hidden_text",hidden_text);
        outState.putInt("isHidden",isHidden);
        outState.putString("keybody",keybody);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2000) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                insertImage();
            } else {
                // Permission Denied
                Toast.makeText(SendActivity.this, "没有获取读取图片权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void finish(){
        Intent intent = new Intent();
        setResult(1002,intent);
        super.finish();
    }

    private boolean checkText(){
        //检查文本框
        if(title.getText().toString().equals("")){
            Toast.makeText(getApplicationContext(), "请填写标题", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(recvId.getText().toString().equals("")){
            Toast.makeText(getApplicationContext(), "请填写收信人", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(message_text.getText().toString().equals("")){
            Toast.makeText(getApplicationContext(), "请填写内容", Toast.LENGTH_SHORT).show();
            return false;
        }
        String recvString = URLEncoder.encode(recvId.getText().toString()).replace("；",";").replace(" ","");
        String receives[] = recvString.split(";");
        for(int i = 0; i < receives.length;i++){
            if(receives[i].equals(sendId)){
                //接收人有自己时返回空
                Toast.makeText(getApplicationContext(), "请不要发给自己", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    private String getParams(){
        //拼接表单
        StringBuilder params = new StringBuilder();
        String recvString = URLEncoder.encode(recvId.getText().toString()).replace("；",";").replace(" ","");
        String receives[] = recvString.split(";");
        int count=0;
        for(int i = 0; i < receives.length;i++){
            if(receives[i].equals(""))
            {//空窜不载入

            }else{
                //拼表单
                //String message = message_text.getText().toString();
                params.append("data[").append(count).append("][sendid]=").append(sendId)
                        .append("&data[").append(count).append("][recvid]=").append(receives[i])
                        .append("&data[").append(count).append("][sendtime]=").append(sendTime)
                        .append("&data[").append(count).append("][keybody]=").append(keybody)
                        .append("&data[").append(count).append("][title]=").append(URLEncoder.encode(title.getText().toString()))
                        .append("&data[").append(count).append("][abstract]=").append(URLEncoder.encode(abstract_text))
                        .append("&data[").append(count).append("][common_type]=").append(message_type)
                        .append("&data[").append(count).append("][common_content]=").append(URLEncoder.encode(message_text_toString))
                        .append("&data[").append(count).append("][hidden_type]=").append(hidden_type)
                        .append("&data[").append(count).append("][hidden_content]=").append(URLEncoder.encode(hidden_text))
                        .append("&data[").append(count).append("][ishidden]=").append(isHidden)
                        .append("&data[").append(count).append("][isbin]=").append(0)
                        .append("&data[").append(count).append("][isdel]=").append(0);
                count++;
                if(i!=receives.length-1){
                    params.append("&");
                }
            }
        }
        return params.toString();
    }

    private void insertImage(){
        //跳转到选择图片
        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            //选择图片格式
            intent.setType("image/*");
            intent.putExtra("return-data",true);
            startActivityForResult(intent, 1000);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void insertImfo(Uri selectedImage,String hidden_value){
        //EditText中插入图片
        try {
            //图片内隐藏信息

            String image_path =  getPath(getContentResolver(),selectedImage);
            Bitmap loadImage = setImageSize(image_path,message_text);
            ImageSpan imageSpan = new ImageSpan(getApplicationContext(), loadImage);


            String tempUrl = "<img src=\"" + image_path + "\" alt=\"[{"+hidden_value+"}]\" />";
            SpannableString spannableString = new SpannableString(tempUrl);
            spannableString.setSpan(imageSpan, 0, tempUrl.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 将选择的图片追加到EditText中光标所在位置
            int index = message_text.getSelectionStart();
            // 获取光标所在位置
            Editable edit_text = message_text.getEditableText();
            if (index < 0 || index >= edit_text.length()) {
                edit_text.append(spannableString);
            } else {
                edit_text.insert(index, spannableString);
            }
            //换行
            edit_text.insert(index + spannableString.length(), "\n");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private JSONObject readImgText(String allImgText){
        JSONObject srcAndHidden = new JSONObject();
        String imgArray[];
        ArrayList<String> srcList = new ArrayList<String>();
        ArrayList<String> altList = new ArrayList<String>();
        imgArray = allImgText.split("<img ");
        for(int i = 0;i<imgArray.length;i++){
            if(imgArray[i].equals("")){

            }else{
                try{
                    srcList.add(imgArray[i].substring(imgArray[i].indexOf("src=\"")+5,imgArray[i].indexOf("\" alt=")));
                    altList.add(imgArray[i].substring(imgArray[i].indexOf("alt=\"")+5,imgArray[i].indexOf("\" />")));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        for(int i = 0 ; i<srcList.size();i++){
            try{
                srcAndHidden.put((String)srcList.get(i),(String)altList.get(i));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //imgArray = (String[])srcList.toArray(new String[0]);
        return srcAndHidden;
    }

    private void sendAllMessage(){
        //发邮件
        String text = message_text.getText().toString();
        if(text.length()>8){
            abstract_text = text.substring(0,8)+"...";
            if(abstract_text.indexOf("<img")>=0)
                abstract_text = "[图片]";
        }
        else abstract_text = text;
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        //只有月份少1
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        sendTime=year+"."+month+"."+day;

        String params = getParams();

        Util util = new Util();
        Util.postThread sendMailThread = util.new postThread("/email/sendEmails",getApplicationContext(),params,handler,1);
        sendMailThread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //相应接受数据
            if (msg.what == 1) {
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){//发送成功
                        new AlertDialog.Builder(SendActivity.this).setTitle("提示")//设置对话框标题
                                .setMessage("发送成功")//设置显示的内容
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        if(alertDialog!=null&&alertDialog.isShowing()){
                                            alertDialog.dismiss();
                                        }
                                        finish();
                                    }
                                }).setCancelable(false).show();
                    }else{
                        canClick=1;
                        String message = jsonObject.getString("message");
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 2) {
                //发图片成功
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONObject data = new JSONObject(jsonObject.getString("data"));
                    String message = jsonObject.getString("message");
                    int code = jsonObject.getInt("code");
                    if(code==200){//发送成功
                        Iterator it = data.keys();
                        //逐个替换为服务器图片地址
                        while (it.hasNext()){
                            String localurl=it.next().toString();
                            String url = data.getString(localurl);
                            message_text_toString = message_text_toString.replace(localurl,url);
                            hidden_text = hidden_text.replace(localurl,url);
                        }


                        //发邮件
                        sendAllMessage();

                    }else{
                        canClick=1;
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 3){
                //progress.setText("发送中("+msg.obj.toString()+"%)");
            }
            if (msg.what == 0) {
                canClick=1;
                if(alertDialog!=null){
                    alertDialog.dismiss();
                    alertDialog=null;
                }
                Toast.makeText(getApplicationContext(), "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
